package com.epro.dx.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.epro.dx.R;
import com.epro.dx.pullview.PullToRefreshListView;
import com.epro.dx.util.DpPxUtils;
import com.epro.dx.util.ImageLoaderUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.weipu.common.facade.model.Lines;
import com.weipu.common.facade.model.OrderItemModel;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("ResourceType")
public class MyOrderListAdapter extends BaseAdapter {

	private static final String TAG = "MyOrderListAdapter";

	// 上下文
	private Context context;
	// 订单数据集合
	private ArrayList<OrderItemModel> pageOrdersList;
	private OrderOperatListenner operatListenner;


	public Bitmap defaultBitmap;

	PullToRefreshListView orderListView;

	private String status;
	
	private DisplayImageOptions options;

	public interface OrderOperatListenner {
		void orderConfirmRecept(int position);

		void orderCancel(int position);

		void orderPay(int position);
		
		void checkShippingInfo(String orderNumber,String currency);
	}

	public void setOperatListenner(OrderOperatListenner operatListenner) {
		this.operatListenner = operatListenner;
	}

	public MyOrderListAdapter(Context c,
			ArrayList<OrderItemModel> pageOrdersList,
			PullToRefreshListView orderListView, String status) {
		this.context = c;
		this.pageOrdersList = pageOrdersList;
		this.orderListView = orderListView;
		this.status = status;
		this.orderListView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), true, true));
		options=ImageLoaderUtils.getImageLoaderOptions(R.drawable.item_default,R.drawable.item_default);
	}

	@Override
	public int getCount() {
		if (pageOrdersList.size() != 0) {
			return pageOrdersList.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		if(null!=pageOrdersList&&pageOrdersList.size()!=0){
    		if(pageOrdersList.size()<=position){
    			return null;
    		}
    		return pageOrdersList.get(position);
    	}
    	return null;
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		ViewHolder holder = null;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = View.inflate(context,
					R.layout.item_myorder_orderlist, null);
			holder.orderId = (TextView) convertView
					.findViewById(R.id.tv_myorderlist_orderid);
			holder.orderTime = (TextView) convertView
					.findViewById(R.id.tv_myorderlist_ordertime);
			holder.orderState = (TextView) convertView
					.findViewById(R.id.order_status_tv);
			holder.stateArrow = (ImageView) convertView
					.findViewById(R.id.order_state_arrow);
			holder.imgContainer = (LinearLayout) convertView
					.findViewById(R.id.ll_myorderlist_orderimg_container);
			holder.orderSum = (TextView) convertView
					.findViewById(R.id.tv_myorderlist_ordersum);
			holder.orderCancel = (ImageButton) convertView
					.findViewById(R.id.ibt_myorderlist_cancel);
			holder.orderConfirmReceipt = (ImageButton) convertView
					.findViewById(R.id.ibt_myorderlist_confirm_receipt);
			holder.orderPay = (ImageButton) convertView
					.findViewById(R.id.ibt_myorderlist_pay);
			holder.orderSumContainer = (RelativeLayout) convertView
					.findViewById(R.id.rl_myorderlist_usdsum_container);
			holder.orderItem = (LinearLayout) convertView
					.findViewById(R.id.ll_myorderlist_listitem);
			holder.checkShipping = (ImageButton) convertView.findViewById(R.id.ibt_myorderlist_check_shipping);

			// 设置标记
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
			holder.imgContainer.removeAllViews();
		}

		// 数据Bean
		final OrderItemModel model = pageOrdersList.get(position);
		// 获取与加载图片, 设置图片显示的参数
		List<Lines> lines = model.getLines();
		if (lines != null && lines.size() != 0) {
			int size = lines.size() > 4 ? 4 : lines.size();
			for (int i = 0; i < size; i++) {
				ImageView smileIV = new ImageView(context);
				int frameSize = DpPxUtils.Dp2Px(context, 1);
				smileIV.setPadding(frameSize, frameSize, frameSize, frameSize);
				smileIV.setScaleType(ImageView.ScaleType.FIT_XY);
				smileIV.setBackgroundColor(context.getResources().getColor(
						R.color.image_frame));
				LayoutParams layoutParams = null;
				if (4 == size) {
					layoutParams = new LinearLayout.LayoutParams(
							LayoutParams.MATCH_PARENT,
							LayoutParams.MATCH_PARENT);
					layoutParams.weight = 1;
				} else {
					layoutParams = new LinearLayout.LayoutParams(
							DpPxUtils.Dp2Px(context, 75), DpPxUtils.Dp2Px(
									context, 75));
				}
				// 设置图片显示的宽高

				String smileImageUrl = lines.get(i).getSmileImageUrl();
				// smileIV.setTag(smileImageUrl);
				if(null!=smileImageUrl){
					ImageLoader.getInstance().displayImage(smileImageUrl, smileIV, options);
				}else{
					smileIV.setImageBitmap(getDefault243(context));
				}
				if (i != 0) {
					layoutParams.leftMargin = DpPxUtils.Dp2Px(context, 7);
				}
				layoutParams.topMargin = DpPxUtils.Dp2Px(context, 7);
				layoutParams.bottomMargin = DpPxUtils.Dp2Px(context, 7);
				smileIV.setLayoutParams(layoutParams);
				holder.imgContainer.addView(smileIV);
				holder.imgContainer.setTag(position);
				smileIV.setTag(smileImageUrl);
			}
		}
		// 设置订单号
		holder.orderId.setText(model.getOrderNumber());
		// 设置订单时间
		holder.orderTime.setText(model.getOrderDate());

		boolean canComplete = model.isCanComplete();
		boolean canCancel=model.isCanCancel();
		boolean canRePay = model.isCanRepay();
		boolean isComplete = model.isIsCompleted();
		boolean isCanceled = model.isIsCancelled();
		boolean isShipping = model.isIsShipping();
		boolean isFullShipping = model.isIsFullShipped();
		boolean IsPaymentCompleted = model.isIsPaymentCompleted();
		if(canCancel){
			holder.orderCancel.setVisibility(View.VISIBLE);
		}else{
			holder.orderCancel.setVisibility(View.GONE);
		}
//		if (!isCanceled&&!isComplete&&!isShipping&&!isFullShipping) {
//			holder.orderCancel.setVisibility(View.VISIBLE);
//		} else {
//			holder.orderCancel.setVisibility(View.GONE);
//		}
		if (canRePay) {
			holder.orderPay.setVisibility(View.VISIBLE);
			holder.orderConfirmReceipt.setVisibility(View.GONE);
			holder.orderSumContainer.setVisibility(View.VISIBLE);
		} else {
//			if(!IsPaymentCompleted){
//				holder.orderPay.setVisibility(View.VISIBLE);
//				holder.orderConfirmReceipt.setVisibility(View.GONE);
//				holder.orderSumContainer.setVisibility(View.VISIBLE);
//			}else{
				holder.orderPay.setVisibility(View.GONE);
				holder.orderSumContainer.setVisibility(View.GONE);
//			}
		}

		if (canComplete) {
			holder.orderConfirmReceipt.setVisibility(View.VISIBLE);
			holder.orderPay.setVisibility(View.GONE);
			holder.orderSumContainer.setVisibility(View.GONE);
		} else {
			holder.orderConfirmReceipt.setVisibility(View.GONE);
		}
		
		if (isComplete || isCanceled) {
			holder.orderSumContainer.setVisibility(View.GONE);
			holder.orderPay.setVisibility(View.GONE);
			holder.orderConfirmReceipt.setVisibility(View.GONE);
			holder.orderCancel.setVisibility(View.GONE);
		}
		String orStatus = model.getOrderStatusStr();
//		if ("Cancelled".equals(orStatus)) {
//			holder.orderState.setTextColor(context.getResources().getColor(
//					R.color.gray));
//			holder.stateArrow.setBackgroundResource(R.drawable.gay_arrow);
//		} else {
//			holder.orderState.setTextColor(context.getResources().getColor(
//					R.color.status_orange));
//			holder.stateArrow.setBackgroundResource(R.drawable.yellow_arrow);
//		}
		if(model.isIsCancelled()){
			holder.orderState.setText(R.string.order_state_cancelled);
			holder.orderState.setTextColor(context.getResources().getColor(
					R.color.gray));
			holder.stateArrow.setBackgroundResource(R.drawable.gay_arrow);
		}else{
			holder.orderState.setText(orStatus);
			holder.orderState.setTextColor(context.getResources().getColor(
					R.color.status_orange));
			holder.stateArrow.setBackgroundResource(R.drawable.yellow_arrow);
		}
		//***************添加判断包裹的数量(状态)是否显示查看物流信息的按钮20151230**************************
		if("FullShipment".equals(orStatus)||"PartialShipment".equals(orStatus)
				|| "Completed".equals(orStatus)){
			holder.checkShipping.setVisibility(View.VISIBLE);
		}else{
			holder.checkShipping.setVisibility(View.GONE);
		}
//		holder.checkShipping.setVisibility(model.getPackages()==null?View.GONE:View.VISIBLE);
		//***********************************************************************************

		// // 订单状态的判断与数据设置
		// int orderLight = Integer.parseInt(model.getLight());
		// switch (orderLight) {
		// case ServerConstant.MapKey.ORDER_PAYMENT_RECEVIED:// 已支付
		// holder.orderState.setVisibility(View.VISIBLE);
		// holder.orderState
		// .setText(ServerConstant.MapValue.ORDER_PAYMENT_RECEVIED);
		// holder.orderState.setTextColor(context.getResources().getColor(
		// R.color.status_orange));
		// holder.orderPay.setVisibility(View.GONE);
		// holder.orderConfirmReceipt.setVisibility(View.GONE);
		// holder.orderCancel.setVisibility(View.VISIBLE);
		// holder.orderSumContainer.setVisibility(View.GONE);
		// holder.stateArrow.setBackgroundResource(R.drawable.yellow_arrow);
		// break;
		// case ServerConstant.MapKey.ORDER_PENDING_PAYMENT:// 未支付
		// case ServerConstant.MapKey.ORDER_PARTIAL_PAYMENT://部分支付
		// holder.orderState.setVisibility(View.VISIBLE);
		// if(orderLight==ServerConstant.MapKey.ORDER_PARTIAL_PAYMENT){
		// holder.orderState.setText(ServerConstant.MapValue.ORDER_PARTIAL_PAYMENT);
		// }else{
		// holder.orderState
		// .setText(ServerConstant.MapValue.ORDER_PENDING_PAYMENT);
		// }
		// holder.orderState.setTextColor(context.getResources().getColor(
		// R.color.status_orange));
		// holder.stateArrow.setBackgroundResource(R.drawable.yellow_arrow);
		// holder.orderPay.setVisibility(View.VISIBLE);
		// holder.orderConfirmReceipt.setVisibility(View.GONE);
		// holder.orderCancel.setVisibility(View.VISIBLE);
		// holder.orderSumContainer.setVisibility(View.VISIBLE);
		// break;
		// case ServerConstant.MapKey.ORDER_FULL_SHIPMENT:// 发货
		// holder.orderState.setVisibility(View.VISIBLE);
		// holder.orderState
		// .setText(ServerConstant.MapValue.ORDER_FULL_SHIPMENT);
		// holder.orderState.setTextColor(context.getResources().getColor(
		// R.color.status_orange));
		// holder.orderPay.setVisibility(View.GONE);
		// holder.orderConfirmReceipt.setVisibility(View.VISIBLE);
		// holder.orderCancel.setVisibility(View.GONE);
		// holder.orderSumContainer.setVisibility(View.GONE);
		// holder.stateArrow.setBackgroundResource(R.drawable.yellow_arrow);
		//
		// break;
		// case ServerConstant.MapKey.ORDER_COMPLETED:// 交易完成
		// holder.orderState.setVisibility(View.VISIBLE);
		// holder.orderState.setText(ServerConstant.MapValue.ORDER_COMPLETED);
		// holder.orderState.setTextColor(context.getResources().getColor(
		// R.color.status_orange));
		// holder.stateArrow.setBackgroundResource(R.drawable.yellow_arrow);
		// holder.orderPay.setVisibility(View.GONE);
		// holder.orderConfirmReceipt.setVisibility(View.GONE);
		// holder.orderCancel.setVisibility(View.GONE);
		// holder.orderSumContainer.setVisibility(View.GONE);
		//
		// break;
		// case ServerConstant.MapKey.ORDER_CANCEL:// 交易完成
		// holder.orderState.setVisibility(View.VISIBLE);
		// holder.orderState.setText(ServerConstant.MapValue.ORDER_CANCEL);
		// holder.orderState.setTextColor(context.getResources().getColor(
		// R.color.gray));
		// holder.stateArrow.setBackgroundResource(R.drawable.gay_arrow);
		// holder.orderPay.setVisibility(View.GONE);
		// holder.orderConfirmReceipt.setVisibility(View.GONE);
		// holder.orderCancel.setVisibility(View.GONE);
		// holder.orderSumContainer.setVisibility(View.GONE);
		//
		// break;
		//
		// default:
		// break;
		// }
		String moneyStr = pageOrdersList.get(position).getCurrencyCodeStr();
		// 设置订单金额
		// holder.orderSum.setText(c.getString(R.string.product_price,
		// model.getGrandTotal()));
		holder.orderSum.setText(moneyStr
				+ String.format("%.2f", model.getGrandTotal()));
		// 设置按钮点击事件监听

		// // 点击整个条目进入订单详细页面
		// holder.orderItem.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // 点击进入订单详情页面
		// Intent i = new Intent(context, OrderDetailActivity.class);
		// i.putExtra("OrderNumber", model.getOrderNumber());
		// context.startActivity(i);
		// }
		// });

		// ##################确认收货按钮############################
		holder.orderConfirmReceipt.setTag(R.id.ibt_myorderlist_confirm_receipt,position);
		holder.orderConfirmReceipt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 点击确认收货按钮弹出对话框
				int position = (Integer) v.getTag(R.id.ibt_myorderlist_confirm_receipt);
				showDialog(position, 2);
			}
		});
		// ###################支付按钮##############################
		holder.orderPay.setTag(R.id.ibt_myorderlist_pay,position);
		holder.orderPay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int position = (Integer) v.getTag(R.id.ibt_myorderlist_pay);
				OrderItemModel orderModel = pageOrdersList.get(position);
				if (!"840".equals(orderModel.getCurrencyCode())) {
					Toast.makeText(
							context,
							context.getResources().getString(
									R.string.no_support_payment), 0).show();
					return;
				}
				if (null != operatListenner) {
					operatListenner.orderPay(position);
				}
				// 点击按钮执行支付逻辑
				// showDialog();
				// Toast.makeText(c, "支付订单", 0).show();
			}
		});
		// ###################取消按钮##############################
		holder.orderCancel.setTag(R.id.ibt_myorderlist_cancel,position);
		holder.orderCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 点击执行取消订单的逻辑
				// Toast.makeText(c, "取消订单", 0).show();
				int position = (Integer) v.getTag(R.id.ibt_myorderlist_cancel);
				if (null != operatListenner) {
					operatListenner.orderCancel(position);
				}

			}
		});
		//####################查看物流#################################
		holder.checkShipping.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// 调用接口获取物流信息数据判断跳转
				operatListenner.checkShippingInfo(model.getOrderNumber(),model.getCurrencyCodeStr());
			}
		});
		return convertView;
	}

	// 取消订单操作

	private AlertDialog dialog;

	/**
	 * 显示对话框
	 * 
	 * @param position
	 *            item position
	 * @param type
	 *            对话框类型 0代表pay 1代表cancel 2代表确认收货
	 */
	protected void showDialog(final int position, final int type) {

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		View view = View
				.inflate(context, R.layout.dialog_confirm_receipt, null);

		ImageButton no = (ImageButton) view
				.findViewById(R.id.dialog_confirm_receipt_no);
		ImageButton yes = (ImageButton) view
				.findViewById(R.id.dialog_confirm_receipt_yes);

		// 按钮点击事件
		no.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 点击no按钮隐藏弹窗
				dialog.dismiss();

			}
		});
		yes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 点击yes执行确认收货逻辑
				switch (type) {
				case 0:
					break;
				case 1:

					break;
				case 2:
					if (null != operatListenner) {
						operatListenner.orderConfirmRecept(position);
					}
					dialog.dismiss();
					break;

				default:
					break;
				}

			}
		});
		builder.setView(view);
		dialog = builder.create();
		dialog.show();
	}

	/**
	 * @author TonyYang 页面控件缓存
	 */
	private class ViewHolder {

		// 整体可点击
		LinearLayout orderItem;

		// 订单号
		TextView orderId;

		// 下单时间
		TextView orderTime;

		// 订单状态
		TextView orderState;

		ImageView stateArrow;

		// 订单图片
		LinearLayout imgContainer;

		// 订单金额
		TextView orderSum;

		// 支付按钮
		ImageButton orderPay;

		// 确认收获按钮
		ImageButton orderConfirmReceipt;

		// 取消支付按钮
		ImageButton orderCancel;

		// 查看物流信息按钮
		ImageButton checkShipping;
		
		// 显示金额的布局用于控制是否显示
		RelativeLayout orderSumContainer;
	}

	/**
	 * 获取默认图片
	 * 
	 * @param context
	 */
	public Bitmap getDefault243(Context context) {
		if (null == defaultBitmap) {
			InputStream is = context.getResources().openRawResource(
					R.drawable.item_default);
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 1;
			defaultBitmap = BitmapFactory.decodeStream(is, null, options);
		}
		return defaultBitmap;
	}
	
}
